<template>
  <div v-loading="loading">
    <div class="qup-title-box"><span class="border" /><span>门店整体评分</span></div>
    <el-table
      :key="renderKey"
      :data="[{}]"
      border
      max-height="700"
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      style="width: 100%"
    >
      <el-table-column
        v-for="(item,index) in propTable"
        :key="index"
        show-overflow-tooltip
        header-align="center"
        align="center"
        :label="item.name?(item.name+'(' +item.ratio +'%'+')'):item.titleName"
      >
        <template>
          {{ item.score||item.headName }}
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom:60px">
      <div class="qup-title-box"><span class="border" /><span>装修跟进评分</span></div>
      <div v-for="(item,index) in categoryList" :key="index" style="margin-bottom:30px">
        <el-table
          :data="item.scoreDTOS"
          border
          show-summary
          max-height="700"
          :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
          style="width: 100%"
        >
          <el-table-column header-align="center" :label="item.scoreDTOS&&item.scoreDTOS.length&&item.scoreDTOS[0].decorateTypeName">
            <!-- <el-table-column header-align="center" prop="decorateTypeName" label="评价类型" /> -->
            <el-table-column header-align="center" width="120" prop="decorateCategoryName" label="类别" />
            <el-table-column header-align="center" prop="decorateProjectName" label="项目" />
            <el-table-column header-align="center" min-width="260" prop="decorateItemContext" label="评价要求及基本原则" />
            <el-table-column header-align="center" min-width="160" :label="`评定分值(${item.standardScore}分/问题)`">
              <template>
                <el-checkbox-group v-model="checkedLevel" disabled>
                  <el-checkbox v-for="l in levelOption" :key="l" :label="l">{{ l }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column header-align="center" :label="'卖场面积'+'('+shopArea+'㎡)'">
            <el-table-column width="80" header-align="center" prop="score" label="分值" />
            <el-table-column header-align="center" min-width="100" label="问题数">
              <template slot-scope="scope">
                <el-input-number
                  v-if="!isDetail"
                  v-model="scope.row.problemNum"
                  :min="0"
                  size="mini"
                  style="width:90%"
                  @change="changeProblemNum(index,scope.$index,scope.row,item.standardScore)"
                />
                <span v-else>
                  {{ scope.row.problemNum }}
                </span>
              </template>
            </el-table-column>
            <el-table-column width="80" header-align="center" prop="scoreValue" label="得分" />
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import { queryEvaluateTypeById, queryEvaluateTypeList, queryShopScoreList, saveShopEvaluate, queryEvaluateDetailList } from '@/api/marketService/dailyPatrol'
export default {
  name: 'ShopEvaluate',
  props: {
    patrolId: {
      type: String,
      default: ''
    },
    shopCode: {
      type: String,
      default: ''
    },
    shopArea: {
      type: [String, Number],
      default: 0
    },
    picConfigId: {
      type: String,
      default: ''
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      checkedLevel: [],
      levelOption: ['好', '较好', '较差', '差'],
      categoryList: [],
      typeIdList: [], // 类型id
      propTable: [],
      propList: [],
      renderKey: false
      // activeTypeId: ''
    }
  },
  watch: {
    patrolId: {
      handler(v) {
        if (!v) return
        this.getEvaluateType()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    async saveData() {
      return new Promise((resolve, reject) => {
        const tempList = this.categoryList
        let requestMethod = 'post'
        tempList.forEach(v => {
          const obj = this.typeIdList.find(i => i.decorateTypeId === v.decorateTypeId)
          this.$set(v, 'patrolId', this.patrolId)
          if (obj && obj.id) {
            this.$set(v, 'id', obj.id)
            requestMethod = 'put'// 新增或修改
          }
        })
        saveShopEvaluate(tempList, requestMethod).then(res => {
          if (res.success) {
            this.$message.success('保存成功')
            resolve()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    countLastScore(index, key, decorateTypeId, data) {
      const lastScore = this.categoryList[index].scoreDTOS.reduce((prev, curr) => {
        const value = Number(curr.scoreValue || 0)
        return (prev || 0) + value
      }, 0)
      const keyIndex = this.propTable.findIndex(v => v.id === decorateTypeId)
      if (keyIndex !== -1) this.propTable[keyIndex].score = lastScore
      const countScore = this.propTable.reduce((prev, curr) => {
        const temp = Number(curr.ratio || 0)
        const value = Number(curr.score || 0) * temp / 100
        return prev + value
      }, 0)
      this.propTable[this.propTable.length - 1].score = countScore.toFixed(0)
      this.renderKey = !this.renderKey
    },
    changeProblemNum(index, key, { problemNum, decorateTypeId }, standardScore) {
      let deductScore = 0
      // 卖场大于1000
      if (Number(this.shopArea || 0) >= 1000) {
        deductScore = standardScore * problemNum * (Number(this.shopArea || 0) / 1000)
      }
      // 卖场小于1000
      if (Number(this.shopArea || 0) < 1000) {
        deductScore = (1000 / Number(this.shopArea || 0)) * standardScore * problemNum
      }
      const temp = (Number(this.categoryList[index].scoreDTOS[key].score) - deductScore)
      const getScore = temp < 0 ? 0 : temp.toFixed(0)
      this.$set(this.categoryList[index].scoreDTOS[key], 'scoreValue', getScore)
      this.countLastScore(index, key, decorateTypeId)// 计算单个类型总分
    },
    handleQueryList(list) {
      this.loading = true
      const tempList = list.map((v, index) => {
        return new Promise((resolve, reject) => {
          queryShopScoreList(this.patrolId, v.id).then(res => {
            if (res.success && res.data.records && res.data.records.length) {
              resolve({ standardScore: v.score, decorateTypeId: v.id, scoreDTOS: res.data.records })
            } else {
              queryEvaluateDetailList(v.id).then(res => {
                if (res.success) {
                  const tempArr = res.data.map(v => { return { ...v, scoreValue: Number(v.score || 0), patrolId: this.patrolId } })
                  resolve({ standardScore: v.score, decorateTypeId: v.id, scoreDTOS: tempArr })
                } else {
                  reject('获取失败')
                  this.loading = false
                }
              })
            }
          })
        })
      })
      Promise.all(tempList).then(res => {
        this.categoryList = res
        this.categoryList.map((v, index) => this.countLastScore(index, 0, v.decorateTypeId))
        this.loading = false
      })
    },
    getEvaluateType() {
      queryEvaluateTypeList(this.patrolId).then(res => {
        if (res.success) {
          this.handleQueryList(res.data.records)
          this.propTable = [{ name: '', headName: '得分' }, ...res.data.records, { score: 0, titleName: '整体形象得分' }]
        }
      })
      queryEvaluateTypeById(this.patrolId).then(res => {
        if (res.success) {
          this.typeIdList = res.data || []
        }
      })
    }
  }

}
</script>
